package com.mask.socket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * ClassName TCPServer
 * Create by hx
 * Date 2021/9/21 10:48 上午
 */

public class TCPServer {
    private static final int PORT = 8189;

    public void listen(){
        ServerSocket serverSocket = null;
        Socket socket = null;
        OutputStream outputStream = null;
        try {
            serverSocket = new ServerSocket(PORT);
            socket = serverSocket.accept();
            System.out.println("获取地址为:" + socket.getInetAddress()+"的客户端对象");
            outputStream = socket.getOutputStream();
            String s = "获取成功";
            outputStream.write(s.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("结束与客户端交换数据!");
    }
}
